﻿using System;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace Morus.Presentation
{
    public abstract class Presenter<TView> : IPresenter<TView>
        where TView : class, IView
    {
        private readonly TView _view;

        protected Presenter(TView view)
        {
            InitializeDefaultModel(view);
            _view = view;
        }

        public TView View
        {
            get { return _view; }
        }

        public IMessageBus Messages { get; set; }

        private static void InitializeDefaultModel(TView view)
        {
            var modelType = view.GetType()
                .GetInterfaces()
                .Where(t => t.IsGenericType)
                .Where(t => t.GetGenericTypeDefinition() == typeof(IView<>))
                .Select(t => t.GetGenericArguments().Single())
                .FirstOrDefault();

            if (modelType == null)
            {
                return;
            }

            var defaultModel = Activator.CreateInstance(modelType);

            typeof(IView<>)
                .MakeGenericType(modelType)
                .GetProperty("Model")
                .SetValue(view, defaultModel);
        }
    }
}